package com.vng.zini.gifapp.activity;

import java.util.ArrayList;

import com.vng.zini.gifapp.activity.CameraActivity;
import com.vng.zini.gifapp.components.GIFCamera;
import com.vng.zini.gifapp.components.GIFMediaRecorder;
import com.vng.zini.gifapp.components.Images;
import com.vng.zini.gifapp.components.MyCameraSurfaceView;
import com.vng.zini.gifapp.components.SettingDialog;
import com.vng.zini.gifapp.config.AppConstant;
import com.vng.zini.gifapp.config.AppParameters;
import com.vng.zini.gifapp.utils.VideoManager;
import com.vng.zini.giffapp.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class CameraActivity extends Activity{
	private Camera myCamera;
	private MyCameraSurfaceView myCameraSurfaceView;
	//private MediaRecorder mediaRecorder;
	private ArrayList<Bitmap> lBitmap;
	private ImageButton startButton, importPicture,btn_FB, btn_flash;
	private boolean recording;
	private TextView tv_time;
	private CameraTime cam_th;
	private ProgressDialog progressDialog;
	private ImageButton btn_setting,next;
	private final Context context = this;
	private static int RESULT_LOAD_IMAGE = 1;
	private GIFMediaRecorder mediaRecorder;
	private ImageView iv_next;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		System.out.println("on create camera activity");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_takepicture3);
		
		initParameter();
		cameraInit();
		addListenerOnButton();
	}
	
	private void initParameter() {
		AppParameters.time_sleep = 333;
		AppParameters.numberFrames = 20;
		AppParameters.camera_time = AppParameters.numberFrames;
		AppParameters.frameSmall = true;
		AppParameters.cameraID = 1;
		AppParameters.listSize = null;
		AppParameters.isLightOn = false;
		tv_time = (TextView) findViewById(R.id.tv_camera_2);
		tv_time.setText(String.valueOf(AppParameters.camera_time));
		recording = false;

		AppParameters.numberCam = Camera.getNumberOfCameras();
		iv_next = (ImageView) findViewById(R.id.topbar_black_next_arrow);
		iv_next.setVisibility(View.INVISIBLE);
	}
	
	private void cameraInit() {
		// Get Camera for preview
		
		myCamera = GIFCamera.getCameraInstance();
		if (myCamera == null) {
			Toast.makeText(CameraActivity.this, "Fail to get Camera",
					Toast.LENGTH_LONG).show();
		}

		myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
		FrameLayout myCameraPreview = (FrameLayout) findViewById(R.id.videoview_2);
		myCameraPreview.addView(myCameraSurfaceView);
	}
	
	private void cameraInit2() {
		// Get Camera for preview
		myCamera = GIFCamera.getCameraInstance();
		if (myCamera == null) {
			Toast.makeText(CameraActivity.this, "Fail to get Camera",
					Toast.LENGTH_LONG).show();
		}

		myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
		FrameLayout myCameraPreview = (FrameLayout) findViewById(R.id.videoview_2);
		myCameraPreview.removeAllViews();
		myCameraPreview.addView(myCameraSurfaceView);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		System.out.println("on start camera activity");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		//initParameter();
		//cameraInit();
		System.out.println("on restart camera activity");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		System.out.println("on resume camera activity");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		System.out.println("on stop camera activity");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		System.out.println("on destroy camera activity");
		if(mediaRecorder !=null){
			mediaRecorder.releaseMediaRecorder(); // if you are using MediaRecorder, release it
								// first
		}
		releaseCamera(); // release the camera immediately on pause event
		if(cam_th !=null){
			cam_th.interrupt();
		}
	}

	private void configParamsBeforeRecording(){
		int id = R.drawable.take_btn_pause;
		startButton.setImageResource(id);
		next.setVisibility(View.VISIBLE);
		iv_next.setVisibility(View.VISIBLE);
	}
	
	private void addListenerOnButton() {
		startButton = (ImageButton) findViewById(R.id.btn_take_camera);
		btn_setting = (ImageButton) findViewById(R.id.btn_setting_2);
		importPicture = (ImageButton) findViewById(R.id.btn_import);
		next = (ImageButton) findViewById(R.id.topbar_black_right_btn);
		next.setVisibility(View.INVISIBLE);
		btn_FB = (ImageButton) findViewById(R.id.btn_rotate_default);
		btn_flash = (ImageButton) findViewById(R.id.btn_torch_light);
		startButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (recording) {
					// stop recording and release camera
					mediaRecorder.stop(); // stop the recording
					mediaRecorder.releaseMediaRecorder(); // release the MediaRecorder object

					// finish();
				} else {

					// Release Camera before MediaRecorder start
					
					configParamsBeforeRecording();
					releaseCamera();
					mediaRecorder = new GIFMediaRecorder(myCameraSurfaceView, myCamera);
					if (!mediaRecorder.prepareMediaRecorder()) {
						Toast.makeText(CameraActivity.this,
								"Fail in prepareMediaRecorder()!\n - Ended -",
								Toast.LENGTH_LONG).show();
						finish();
					}

					mediaRecorder.start();
					recording = true;
					cam_th = new CameraTime();
					cam_th.start();
				}
			}
		});

		btn_setting.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				SettingDialog settingDialog = new SettingDialog(context);
				settingDialog.show();
			}
		});
		
		btn_FB.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				releaseCamera();
				if(AppParameters.cameraID==1){
					btn_FB.setImageResource(R.drawable.rotate_pressed);
					AppParameters.cameraID = 0;
				}
				else{
					btn_FB.setImageResource(R.drawable.rotate_default);
					AppParameters.cameraID = 1;
				}
				cameraInit2();
			}
		});
		
		importPicture.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Intent i = new Intent(
				//Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				//startActivityForResult(i, RESULT_LOAD_IMAGE);
				Toast.makeText(CameraActivity.this,
						"Haven't suported yet",
						Toast.LENGTH_SHORT).show();
			}
		});
		
		btn_flash.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!AppParameters.isLightOn){
					Parameters p = myCamera.getParameters();
                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    myCamera.setParameters(p);
                    myCamera.startPreview();
                    AppParameters.isLightOn = true;
				}
				else{
					Parameters p = myCamera.getParameters();
                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    myCamera.setParameters(p);
                    myCamera.startPreview();
                    AppParameters.isLightOn = false;
				}
			}
		});
		
		next.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});

	}
	
	

	@Override
	protected void onPause() {
		super.onPause();
		System.out.println("on pause camera activity");
	}
	
	

	private void releaseCamera() {
		if (myCamera != null) {
			myCamera.stopPreview();
			myCamera.release(); // release the camera for other applications
			myCamera = null;
		}
	}

	
	private class CameraTime extends Thread {
		public void run() {
			while (true) {
				CameraActivity.this.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						System.out.println(AppParameters.camera_time);
						tv_time.setText(String.valueOf(AppParameters.camera_time));
					}
				});

				try {
					sleep(AppParameters.time_sleep);

					AppParameters.camera_time--;
					if (AppParameters.camera_time == -1) {
						AppParameters.camera_time = 20;
						mediaRecorder.stop(); // stop the recording
						mediaRecorder.releaseMediaRecorder(); // release the MediaRecorder
												// object
					
						
						CameraActivity.this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								progressDialog = ProgressDialog.show(CameraActivity.this, "", "Đang tải ...");
							}

						});
						VideoManager.open(context,"/sdcard/myvideo.mp4");
						lBitmap = VideoManager.extractVideo2BitmapList(AppConstant.EXTRACT_FFMPEG_MODE);
						CameraActivity.this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								progressDialog.dismiss();
								Intent intent = new Intent(CameraActivity.this,
										ImagePreviewActivity.class);

								Images.listImage = lBitmap;
								startActivity(intent);
							}

						});
						break;
					}
				} catch (Exception e) {
					//System.out.println(e.getMessage());
					e.printStackTrace();
					this.interrupt();
					
				}
			}
		}

	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
         
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
 
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
 
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
             
            
         
        }
     
     
    }

	
}
